package com.itheima.reggie.view;

import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.servlet.view.document.AbstractXlsxView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

public class ExcelView extends AbstractXlsxView {

    @Override
    protected void buildExcelDocument(Map<String, Object> model, Workbook workbook,
                                      HttpServletRequest request, HttpServletResponse response) throws Exception {

        // 获取数据模型中的数据
        List<Map<String, String>> dataList = (List<Map<String, String>>) model.get("dataList");

        // 创建工作表并设置标题行
        Sheet sheet = workbook.createSheet("Data");
        Row header = sheet.createRow(0);
        header.createCell(0).setCellValue("like");
        header.createCell(1).setCellValue("eat");
        header.createCell(2).setCellValue("sport");

        // 填充数据行
        int rowNum = 1;
        for (Map<String, String> map : dataList) {
            Row row = sheet.createRow(rowNum++);
            row.createCell(0).setCellValue(map.get("like"));
            row.createCell(1).setCellValue(map.get("eat"));
            row.createCell(2).setCellValue(map.get("sport"));
        }

        // 设置响应头信息
//        response.setHeader("Content-Disposition", "attachment; filename=\"data.xlsx\"");
        response.setHeader("Content-Disposition", "inline; filename=\"data.xlsx\"");

    }
}
